<template>
	<view class="teacher-profile">
		<!-- 主内容区域 -->
		<view class="content">
			<!-- 顶部头像和信息区域 -->
			<view class="profile-header animate__animated animate__fadeIn">
				<view class="avatar-container" @click="updateAver">
					<image class="avatar" :src="teacher.avatarUrl" mode="aspectFill"></image>
					<view class="status-indicator" :class="status"></view>
					<view class="edit-overlay">
						<uni-icons type="camera" size="24" color="#fff"></uni-icons>
					</view>
				</view>

				<view class="info-section">
					<text class="name">{{teacher.name || '教师姓名'}}</text>
					<text class="title">{{teacher.title || '高级教师'}}</text>

					<view class="stats-row">
						<view class="stat-item">
							<text class="stat-value">{{teacher.courseCount || 0}}</text>
							<text class="stat-label">授课科目</text>
						</view>
						<view class="stat-divider"></view>
						<view class="stat-item" @click="money">
							<text class="stat-value">​**​*</text>
							<text class="stat-label">基本收入</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 个人信息卡片 -->
			<view class="info-card animate__animated animate__fadeInUp">
				<view class="card-header">
					<text class="card-title">个人简介</text>
				</view>

				<view class="card-content">
					<text class="bio-text" @click="showFullBio">
						{{teacher.bio ? (showFullBioText ? teacher.bio : teacher.bio.slice(0, 30) + '...') : '暂无个人简介'}}
						<text class="read-more"
							v-if="teacher.bio && teacher.bio.length > 10 && !showFullBioText">查看更多</text>
					</text>
				</view>
			</view>

			<!-- 授课科目卡片 -->
			<view class="courses-card animate__animated animate__fadeInUp" style="animation-delay: 0.1s">
				<view class="card-header">
					<text class="card-title">授课科目</text>
				</view>

				<view class="courses-grid">
					<view class="course-item" v-for="(course, index) in mergedSubjects" :key="index">
						<view class="course-char">{{getSubjectChar(course.subjects)}}</view>
						<text class="course-name">{{course.name}}</text>
					</view>
				</view>
			</view>

			<!-- 打卡状态卡片 -->
			<view class="attendance-card animate__animated animate__fadeInUp" style="animation-delay: 0.2s">
				<view class="card-header">
					<view class="month-control">
						<uni-icons type="arrow-left" size="20" @click="prevMonth"></uni-icons>
						<text class="month-title">{{displayMonth}}</text>
						<uni-icons type="arrow-right" size="20" @click="nextMonth"></uni-icons>
					</view>
					<view class="legend">
						<view class="legend-item">
							<view class="legend-color morning"></view>
							<text>上班</text>
						</view>
						<view class="legend-item">
							<view class="legend-color evening"></view>
							<text>下班</text>
						</view>
					</view>
				</view>

				<view class="attendance-calendar">
					<view class="calendar-header">
						<text v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">{{day}}</text>
					</view>

					<view class="calendar-days">
						<view v-for="(day, index) in calendarDays" :key="index" :class="['day', { 
              'today': day.isToday, 
              'current-month': day.isCurrentMonth
            }]" @click="showDayDetail(day)">
							<text>{{day.date}}</text>
							<view class="check-marks">
								<view v-if="day.morningChecked" class="check-mark morning"></view>
								<view v-if="day.eveningChecked" class="check-mark evening"></view>
							</view>
						</view>
					</view>
				</view>

				<view class="attendance-stats">
					<view class="stat-item">
						<text class="stat-value">{{attendanceData.checkedDays}}</text>
						<text class="stat-label">已打卡</text>
					</view>
					<view class="stat-divider"></view>
					<view class="stat-item">
						<text class="stat-value">{{attendanceData.shouldCheckDays}}</text>
						<text class="stat-label">应打卡</text>
					</view>
					<view class="stat-divider"></view>
					<view class="stat-item">
						<text class="stat-value">{{attendanceData.attendanceRate}}%</text>
						<text class="stat-label">出勤率</text>
					</view>
				</view>
			</view>

			<!-- 底部操作按钮 -->
			<view class="action-buttons animate__animated animate__fadeInUp" style="animation-delay: 0.3s">
				<button class="action-btn share-btn" @click="edit">
					<uni-icons type="share" size="20" color="#fff"></uni-icons>
					<text>编辑资料</text>
				</button>
				<button class="action-btn logout-btn" @click="zhuxiao">
					<uni-icons type="redo" size="20" color="#fff"></uni-icons>
					<text>退出登录</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				status: 'offline',
				teacher: {
					courses: [],
					attendance: {}
				},
				showFullBioText: false,
				mergedSubjects: [],
				checkData: [],
				currentViewYear: new Date().getFullYear(),
				currentViewMonth: new Date().getMonth()
			}
		},
		computed: {
			displayMonth() {
				return `${this.currentViewYear}年${this.currentViewMonth + 1}月`;
			},
			attendanceData() {
				let checkedDays = 0;
				let shouldCheckDays = 0;
				let fullDays = 0;

				const currentYear = this.currentViewYear;
				const currentMonth = this.currentViewMonth;
				const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();

				// 计算当月工作日
				for (let i = 1; i <= daysInMonth; i++) {
					const dayOfWeek = new Date(currentYear, currentMonth, i).getDay();
					if (dayOfWeek > 0 && dayOfWeek < 6) {
						shouldCheckDays++;
					}
				}

				// 计算实际打卡情况
				const currentMonthStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}`;

				this.checkData.forEach(item => {
					if (item.date.startsWith(currentMonthStr)) {
						if (item.checkInTime) checkedDays++;
						if (item.checkInTime && item.checkOutTime) fullDays++;
					}
				});

				const attendanceRate = shouldCheckDays > 0 ?
					Math.round((checkedDays / shouldCheckDays) * 100) : 0;

				return {
					checkedDays,
					shouldCheckDays,
					attendanceRate,
					fullDays
				};
			},
			calendarDays() {
				const today = new Date();
				const currentYear = this.currentViewYear;
				const currentMonth = this.currentViewMonth;
				const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay();
				const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();

				let days = [];

				// 上个月的天数
				const prevMonthDays = firstDayOfMonth;
				const prevMonth = new Date(currentYear, currentMonth - 1, 1);
				const daysInPrevMonth = new Date(currentYear, currentMonth, 0).getDate();

				for (let i = prevMonthDays - 1; i >= 0; i--) {
					days.push({
						date: daysInPrevMonth - i,
						isCurrentMonth: false,
						isToday: false,
						morningChecked: false,
						eveningChecked: false
					});
				}

				// 当前月的天数
				for (let i = 1; i <= daysInMonth; i++) {
					const dateStr =
						`${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`;

					// 查找当天的打卡记录
					const checkRecord = this.checkData.find(item => item.date === dateStr);
					const morningChecked = checkRecord && checkRecord.checkInTime;
					const eveningChecked = checkRecord && checkRecord.checkOutTime;
					const morningTime = morningChecked ? checkRecord.checkInTime.split(' ')[1] : null;
					const eveningTime = eveningChecked ? checkRecord.checkOutTime.split(' ')[1] : null;

					days.push({
						date: i,
						isCurrentMonth: true,
						isToday: i === today.getDate() && 
                                 currentMonth === today.getMonth() && 
                                 currentYear === today.getFullYear(),
						morningChecked,
						eveningChecked,
						morningTime,
						eveningTime
					});
				}

				// 下个月的天数
				const totalCells = Math.ceil((days.length) / 7) * 7;
				const nextMonthDays = totalCells - days.length;

				for (let i = 1; i <= nextMonthDays; i++) {
					days.push({
						date: i,
						isCurrentMonth: false,
						isToday: false,
						morningChecked: false,
						eveningChecked: false
					});
				}

				return days;
			}
		},
		methods: {
			prevMonth() {
				if (this.currentViewMonth === 0) {
					this.currentViewMonth = 11;
					this.currentViewYear--;
				} else {
					this.currentViewMonth--;
				}
			},
			nextMonth() {
				if (this.currentViewMonth === 11) {
					this.currentViewMonth = 0;
					this.currentViewYear++;
				} else {
					this.currentViewMonth++;
				}
			},
			money() {
				uni.navigateTo({
					url:"/pages/myDaka/myDaka"
				})
			},
			getSubjectChar(subjects) {
				const firstSubject = subjects.split('、')[0];
				return firstSubject ? firstSubject.charAt(0) : '科';
			},
			mergeSubjects(subjects) {
				const gradeMap = {};
				subjects.forEach(subject => {
					if (!gradeMap[subject.grade]) {
						gradeMap[subject.grade] = [];
					}
					gradeMap[subject.grade].push(subject.subject);
				});

				return Object.keys(gradeMap).map(grade => {
					return {
						grade: grade,
						subjects: gradeMap[grade].join('、'),
						name: `${grade}${gradeMap[grade].join('、')}`
					};
				});
			},
			showDayDetail(day) {
				if (!day.isCurrentMonth) return;
				// console.log(day)
				let message = '';
				if (day.morningChecked && day.eveningChecked) {
					message = `完整打卡\n上班: ${day.morningChecked}\n下班: ${day.eveningChecked}`;
				} else if (day.morningChecked) {
					message = `已上班打卡: ${day.morningChecked}\n未下班打卡`;
				} else if (day.eveningChecked) {
					message = `未上班打卡\n已下班打卡: ${day.eveningChecked}`;
				} else {
					message = '今日未打卡';
				}

				uni.showModal({
					title: `${this.currentViewMonth + 1}月${day.date}日打卡详情`,
					content: message,
					showCancel: false
				});
			},
			updateAver() {
				uni.navigateTo({
					url: "/pages/unloadAver/unloadAver"
				});
			},
			zhuxiao() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							uni.removeStorageSync('teacher');
							uni.navigateTo({
								url: "/pages/login/login"
							});
						}
					}
				});
			},
			edit() {
				uni.navigateTo({
					url: "/pages/myInfo/myInfo"
				});
			},
			getCheckData() {
				uni.request({
					url: `${globalVariable}/getAllTeacherCheck?teacherId=${this.teacher.teacherId}`,
					success: (res) => {
						if (res.data.status === 1) {
							this.checkData = res.data.data;
						}
					}
				});
			},
			getData() {
				let that = this;
				uni.getStorage({
					key: "teacher",
					success: function(res) {
						that.teacher = res.data;
						if (that.teacher.avatarUrl == null) {
							that.teacher.avatarUrl = "/static/aver.jpg";
						} else {
							const timestamp = new Date().getTime();
							that.teacher.avatarUrl =
								`${globalVariable}/get/${that.teacher.avatarUrl}?t=${timestamp}`;
						}

						// 获取教师科目数据
						uni.request({
							url: `${globalVariable}/getTeacherSubjectAll?teacherId=${that.teacher.teacherId}`,
							success: (res) => {
								if (res.data.status === 1) {
									that.mergedSubjects = that.mergeSubjects(res.data.data);
									that.teacher.courseCount = that.mergedSubjects.length;
								}
							}
						});

						// 获取打卡数据
						that.getCheckData();
					}
				});
			},
			showFullBio() {
				if (this.teacher.bio && this.teacher.bio.length > 10) {
					this.showFullBioText = !this.showFullBioText;
				}
			}
		},
		onShow() {
			this.getData();
			setTimeout(() => {
				this.status = 'online';
			}, 1000);

			if (this.teacher.avatarUrl && !this.teacher.avatarUrl.startsWith('/static')) {
				const timestamp = new Date().getTime();
				this.teacher.avatarUrl =
					`${globalVariable}/get/${this.teacher.avatarUrl.split('/').pop().split('?')[0]}?t=${timestamp}`;
			}
		},
		onLoad() {
			this.getData();
		}
	}
</script>

<style>
	/* 引入在线animate.css */
	@import url('/static/animate.css');

	/* 月份切换控件样式 */
	.month-control {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 30rpx;
		margin-bottom: 20rpx;
	}

	.month-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		min-width: 180rpx;
		text-align: center;
	}

	/* 打卡日历样式 */
	.legend {
		display: flex;
		align-items: center;
	}

	.legend-item {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
		font-size: 24rpx;
		color: #666;
	}

	.legend-color {
		width: 20rpx;
		height: 20rpx;
		border-radius: 4rpx;
		margin-right: 8rpx;
	}

	.legend-color.morning {
		background-color: #5A7DFF;
	}

	.legend-color.evening {
		background-color: #36D1DC;
	}

	.attendance-stats .stat-value {
		font-size: 36rpx;
		color: #5A7DFF;
		font-weight: bold;
	}

	.attendance-stats .stat-label {
		font-size: 26rpx;
		color: #666;
	}

	.attendance-stats .stat-divider {
		height: 40rpx;
		width: 1rpx;
		background-color: #eee;
		align-self: center;
	}

	.check-marks {
		position: absolute;
		bottom: 8rpx;
		left: 0;
		right: 0;
		display: flex;
		justify-content: center;
		gap: 10rpx;
	}

	.check-mark {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
	}

	.check-mark.morning {
		background-color: #5A7DFF;
	}

	.check-mark.evening {
		background-color: #36D1DC;
	}

	.course-char {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #5A7DFF 0%, #36D1DC 100%);
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
		font-weight: bold;
		margin: 0 auto 16rpx;
	}

	.course-name {
		font-size: 26rpx;
		color: #333;
		display: block;
		text-align: center;
	}

	.teacher-profile {
		min-height: 100vh;
		position: relative;
		background-color: #f5f7fa;
	}

	.background-gradient {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 300rpx;
		background: linear-gradient(135deg, #5A7DFF 0%, #36D1DC 100%);
		z-index: 0;
	}

	.content {
		position: relative;
		z-index: 1;
		padding: 30rpx;
		padding-top: 0;
	}

	.profile-header {
		display: flex;
		align-items: center;
		padding: 40rpx 0;
		position: relative;
		z-index: 2;
		background-color: #b4b1ff;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.avatar-container {
		width: 150rpx;
		height: 150rpx;
		border-radius: 50%;
		position: relative;
		margin-right: 30rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		transition: transform 0.3s ease;
	}

	.avatar-container:active {
		transform: scale(0.95);
	}

	.avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		border: 4rpx solid #fff;
	}

	.status-indicator {
		position: absolute;
		bottom: 8rpx;
		right: 8rpx;
		width: 24rpx;
		height: 24rpx;
		border-radius: 50%;
		border: 2rpx solid #fff;
		background-color: #ccc;
	}

	.status-indicator.online {
		background-color: #4CAF50;
	}

	.status-indicator.offline {
		background-color: #F44336;
	}

	.edit-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.avatar-container:hover .edit-overlay {
		opacity: 1;
	}

	.info-section {
		flex: 1;
	}

	.name {
		font-size: 40rpx;
		font-weight: 600;
		color: #fff;
		display: block;
		margin-bottom: 8rpx;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
	}

	.title {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.9);
		display: block;
		margin-bottom: 24rpx;
	}

	.stats-row {
		display: flex;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 16rpx;
		padding: 16rpx;
		backdrop-filter: blur(10rpx);
	}

	.stat-item {
		flex: 1;
		text-align: center;
	}

	.stat-value {
		font-size: 32rpx;
		font-weight: 600;
		color: #fff;
		display: block;
	}

	.stat-label {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
		display: block;
		margin-top: 4rpx;
	}

	.stat-divider {
		width: 1rpx;
		background-color: rgba(255, 255, 255, 0.3);
		margin: 0 20rpx;
	}

	.info-card,
	.courses-card,
	.attendance-card {
		background-color: #fff;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.03);
		overflow: hidden;
		transition: transform 0.3s ease, box-shadow 0.3s ease;
	}

	.info-card:active,
	.courses-card:active,
	.attendance-card:active {
		transform: translateY(-4rpx);
		box-shadow: 0 10rpx 25rpx rgba(0, 0, 0, 0.08);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.card-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.edit-btn {
		display: flex;
		align-items: center;
		color: #666;
		font-size: 26rpx;
	}

	.edit-btn text {
		margin-left: 8rpx;
	}

	.card-content {
		padding: 30rpx;
	}

	.bio-text {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}

	.read-more {
		color: #5A7DFF;
		margin-left: 10rpx;
	}

	.courses-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 0 20rpx 20rpx;
	}

	.course-item {
		width: 33.33%;
		padding: 20rpx;
		box-sizing: border-box;
		text-align: center;
	}

	.attendance-calendar {
		padding: 20rpx;
	}

	.calendar-header {
		display: flex;
		margin-bottom: 20rpx;
	}

	.calendar-header text {
		flex: 1;
		text-align: center;
		font-size: 26rpx;
		color: #999;
	}

	.calendar-days {
		display: flex;
		flex-wrap: wrap;
	}

	.day {
		width: 14.28%;
		aspect-ratio: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.day text {
		font-size: 28rpx;
	}

	.day.current-month {
		color: #333;
	}

	.day:not(.current-month) text {
		color: #ccc;
	}

	.day.today {
		background-color: #E3F2FD;
		border-radius: 50%;
	}

	.day.checked::after {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		height: 80%;
		border-radius: 50%;
		background-color: rgba(90, 125, 255, 0.1);
	}

	.action-buttons {
		display: flex;
		margin-top: 40rpx;
	}

	.action-btn {
		flex: 1;
		height: 90rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		font-weight: 500;
		margin: 0 15rpx;
		transition: transform 0.3s ease;
	}

	.action-btn:active {
		transform: scale(0.98);
	}

	.action-btn uni-icons {
		margin-right: 12rpx;
	}

	.share-btn {
		background: linear-gradient(to right, #5A7DFF, #36D1DC);
		color: #fff;
		box-shadow: 0 6rpx 20rpx rgba(90, 125, 255, 0.3);
	}

	.logout-btn {
		background: linear-gradient(to right, #FF5A5F, #FF8E53);
		color: #fff;
		box-shadow: 0 6rpx 20rpx rgba(255, 90, 95, 0.3);
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(40rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.animate-delay-1 {
		animation-delay: 0.1s;
	}

	.animate-delay-2 {
		animation-delay: 0.2s;
	}

	.animate-delay-3 {
		animation-delay: 0.3s;
	}

	.attendance-stats {
		display: flex;
		padding: 30rpx;
		border-top: 1rpx solid #f0f0f0;
		border-radius: 0 0 20rpx 20rpx;
		box-shadow: inset 0 5rpx 10rpx rgba(0, 0, 0, 0.02);
	}

	.attendance-stats .stat-item {
		flex: 1;
		text-align: center;
		padding: 15rpx;
		position: relative;
		transition: all 0.3s ease;
	}

	.attendance-stats .stat-item:active {
		transform: scale(0.95);
	}

	.attendance-stats .stat-value {
		font-size: 38rpx;
		font-weight: bold;
		color: #5A7DFF;
		display: block;
		margin-bottom: 8rpx;
		text-shadow: 0 2rpx 4rpx rgba(90, 125, 255, 0.1);
	}

	.attendance-stats .stat-label {
		font-size: 26rpx;
		color: #666;
		display: block;
		opacity: 0.8;
	}

	.attendance-stats .stat-divider {
		height: 60rpx;
		width: 1rpx;
		background: linear-gradient(to bottom,
				transparent 0%,
				rgba(0, 0, 0, 0.1) 50%,
				transparent 100%);
		align-self: center;
		margin: 0 5rpx;
	}

	/* 添加小图标效果 */
	.attendance-stats .stat-item:nth-child(1)::before {
		content: "✓";
		position: absolute;
		top: 5rpx;
		right: 15rpx;
		font-size: 24rpx;
		color: rgba(90, 125, 255, 0.3);
	}

	.attendance-stats .stat-item:nth-child(3)::after {
		content: "%";
		position: absolute;
		top: 5rpx;
		right: 15rpx;
		font-size: 24rpx;
		color: rgba(90, 125, 255, 0.3);
	}
</style>